<?php
/**
 * Created by PhpStorm.
 * User: Thans
 * Date: 2018/4/18
 * Time: 下午10:28
 */

namespace app\common\model;

use think\Model;
use think\helper\Time;

class ActionModel extends Model
{
    public function pvOrUv($type = 'pv', $time = '')
    {
        switch ($time) {
            case 'day':
                list($start, $end) = Time::today();
                break;
            case 'week':
                list($start, $end) = Time::week();
                break;
            case 'month':
                list($start, $end) = Time::month();
                break;
            default:
                $start = 0;
                $end = time();
                break;
        }
        if ($type == 'pv') {
            $sql = 'ip';
        } else {
            $sql = 'DISTINCT ip';
        }
        $data['count'] = $this->where('add_time', 'between', [$start, $end])
            ->count($sql);
        for ($i = 6; $i >= 0; $i--) {
            list($start) = Time::dayToNow($i);
            $data['counts'][] = $this->where('add_time', 'between', [$start, $start + 60 * 60 * 24])
                ->count($sql);
            $data['keys'][] = date('Y-m-d', $start);
        }
        return $data;
    }

    public function getCountByDevice($type)
    {
        return $this->where('device_type', $type)->count('device_type');
    }

    //获取指定时间内的平均执行时间
    public function getAvgUseTimeByTimes($start, $end)
    {
        $time = $this->where('add_time', 'between', [$start, $end])->avg('use_time') * 1000;
        $time = intval($time);
        return $time;
    }
}